Флаттер: как загрузить данные в main.dart и синхронизировать json с sqflite - PullRequest
0 голосов
/ 25 января 2019

У меня есть http JSON-запрос и sqflite, реализованные в моем приложении на флаттере, но я не уверен, каков наилучший способ синхронизации данных из json в sqflite.Мой инстинкт состоит в том, чтобы загрузить эти данные в мой main.dart, но я не могу заставить его работать.Я получаю будущее >> не может быть назначен на список.Если я загрузлю его в свой gridViewWidget, будет ли это слишком поздно?Должен ли я добавлять данные json в базу данных в методе gridViewWidget fetchFlashCardList?

main.dart:

void main() async {

  var networkObj = new NetworkObject();
//Error Here
  List<FlashCardList> flashCardList = networkObj.fetchFlashCardList();

  runApp(MyApp());
}


class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  final Future<FlashCardList> flashCardList;

  MyApp({Key key, this.flashCardList}): super (key:key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.

        primarySwatch: Colors.blue,
      ),
      home: new GridViewWidget(),

    );
  }


}

gridViewWidget.dart

class GridViewWidget extends StatefulWidget{
  @override
  createState() => new GridViewState();

}

class GridViewState extends State<GridViewWidget>{

  List<FlashCardList> flashCardList;

  Future<List<FlashCardList>> fetchFlashCardList() async{
    final response = await http.get('https://babymozart.org/babymozartq92C9TLa9UMkulL2m81xHdn9u2R92e1e/flutter_test.json');
    //debugPrint (response.body);
    if (response.statusCode == 200) {
      var data = json.decode(response.body);
      var flashCardListData = data["FlashCardList"] as List;
      flashCardList = flashCardListData.map<FlashCardList>((json) => FlashCardList.fromJson(json)).toList();
      debugPrint("Did get data: ${flashCardList.first.name}");
    } else {
      throw Exception('Failed to load post');
    }
    //objects = [sound, flashCardList, flashCards].expand((x) => x).toList();
    return flashCardList;
  }

  @override
  void initState(){
    debugPrint ('debug main.dart');
    super.initState();

  }



  @override
  Widget build(BuildContext context){
    return new Scaffold(
      appBar: new AppBar(
        centerTitle: true,
        title: new Text(Strings.pageTitle),
      ),
      body: FutureBuilder<List<FlashCardList>>(
        future: fetchFlashCardList(),
        builder: (BuildContext context, AsyncSnapshot<List<Object>> snapshot) {
          if (snapshot.hasError)
            return new Text(
              '${snapshot.error}',
              style: TextStyle(color: Colors.red),
            );
          if (snapshot.connectionState == ConnectionState.waiting){
            new Center(child: new CircularProgressIndicator());
          } else {
            return new GridView.builder(

              gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                  maxCrossAxisExtent: 200.0,
                  childAspectRatio: MediaQuery.of(context).size.width/(MediaQuery.of(context).size.height)),
              itemCount: flashCardList.length,
              itemBuilder: (BuildContext context, int index) {
                return _getGridItemUI(context, flashCardList[index]);

                /*return GridTile(header: Text("FlashCards"),
                        child: Text(
                        flashCards[index].name, textAlign: TextAlign.center));*/

              },
            );
          }
        }
      ),
    );
  }

  _getGridItemUI(BuildContext context, FlashCardList item){
    return new InkWell(
      onTap: () {
        _showSnackBar(context, item);
      },
      child: new Card(
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[

              new Image(image: new CachedNetworkImageProvider("https://babymozart.org/babymozartq92C9TLa9UMkulL2m81xHdn9u2R92e1e/image/" + item.image)),
              /*new Expanded(
                child:new Center(
                  child: new Column(
                    children: <Widget>[
                      new SizedBox(height: 8.0),
                      new Expanded(
                        child: AutoSizeText(
                          item.name, maxLines: 1,
                        )
                      )
                    ],
                  ),
                )
              )*/
            ],
        ),
        elevation: 2.0,
        margin: EdgeInsets.all(5.0),
      )
    );
  }

  _showSnackBar(BuildContext context, FlashCardList item){

  }



}
...