0

I have a DateTime data type coming from my database. How to display it in flutter? I keep getting the error Unhandled Exception: type 'String' is not a subtype of type 'DateTime?' I have tried to assign it as a string variable and displayed it as a string but I realized that I needed to make it a DateTime data type so that I can make a format conversion. Please help me. Thank you in advance.

class SensorData{
  String? id, temperature, humidity, FanStatus, MistStatus;
  DateTime? Time;

  SensorData(this.id, this.temperature, this.humidity, this.FanStatus,this.MistStatus,this.Time);

  SensorData.fromJson(Map<String, dynamic>json){
    id = json['id'];
    temperature = json['temperature'];
    humidity = json['humidity'];
    FanStatus = json['FanStatus'];
    MistStatus = json['MistStatus'];
    Time = json['Time'];
  }
}



class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<SensorData> alldata = <SensorData>[];
  List<SensorData> alldataForDisplay = <SensorData>[];

  Future<List<SensorData>> fetchSensorData() async {
    var url = 'http://mushroomdroid.online/dbscript-1.php';
    var response = await http.get(Uri.parse(url));
    var sensordata = <SensorData>[];

    if (response.statusCode == 200) {
      var sensordataJson = json.decode(response.body);
      for (var dataJson in sensordataJson) {
        sensordata.add(SensorData.fromJson(dataJson));
      }
    }
    return sensordata;
  }

  @override
  void initState() {
    fetchSensorData().then((value) {
      setState(() {});
      alldata.addAll(value);
      alldataForDisplay = alldata;
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('ListView'),
        ),
        body: ListView.builder(
          itemBuilder: (context, index) {
            return index == 0 ? _searchBar() : _listItem(index - 1);
          },
          itemCount: alldata.length + 1,
        ));
  }

  _searchBar() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        decoration: InputDecoration(
          hintText: 'Search...'
        ),
        onChanged: (text){
          setState(() {
            alldataForDisplay = alldata.where((data) {
              var time = data.Time.toString();
              return time.contains(text);
            }).toList();
          });
        },
      ),
    );
  }


  _listItem(index) {
    return Card(
      child: Padding(
        padding:
            const EdgeInsets.only(top: 32.0, bottom: 32, left: 16, right: 16),
        child: Column(
          children: <Widget>[
            Text(
              alldataForDisplay[index].id.toString(),
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
            ),
            Text(
              alldataForDisplay[index].Time.toString(),
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
            ),
            Text(
              alldataForDisplay[index].temperature.toString(),
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
            ),
            Text(
              alldataForDisplay[index].humidity.toString(),
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
            ),
            Text(
              alldataForDisplay[index].FanStatus.toString(),
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
            ),
            Text(
              alldata[index].MistStatus.toString(),
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
            ),
          ],
        ),
      ),
    );
  }
}
  • See: [How do I convert a date/time string to a DateTime object in Dart?](https://stackoverflow.com/q/49385303/) – jamesdlin May 12 '22 at 15:44

1 Answers1

0

If you are storing time as epoch, you can use DateTime.fromMillisecondsSinceEpoch(). If you have stored it in this format 1969-07-20 20:18:04Z, then you can use DateTime.parse('1969-07-20 20:18:04Z')

DateTime is one of the most powerful classes of Dart, read more about it here

Chinmay Kabi
  • 489
  • 4
  • 9
  • I am getting the data like this: [{"id":"1603","temperature":"29.55","humidity":"74.99","FanStatus":"ON","MistStatus":"ON \r\n","Time":"2022-05-12 13:48:41"}... The time is provided by the database. – Mark Allen Molina May 12 '22 at 13:52
  • ```DateTime.parse('2022-05-12 13:48:41')``` will work in this case – Chinmay Kabi May 13 '22 at 05:28