Flutter:如何更新从REST API获取的数据库并将其保存到数据库。拉动刷新时需要更新数据

时间:2019-11-19 09:11:26

标签: flutter sqflite

我需要刷新后才能更新数据。我正在从json url提取数据并将数据保存到db并在listview builder中显示,但是每当json api正在更新数据时,数据都是静态的,因此请帮助我。我使用了here中的示例。下面是我的代码

articles.dart

class Articleslist extends StatefulWidget {
  @override
  Articleslist({this.title}) : super();
  final String title;
  _OurArticleslistPageState createState() => new _OurArticleslistPageState();
}

class _OurArticleslistPageState extends State<Articleslist> {
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
  new GlobalKey<RefreshIndicatorState>();
  ScrollController _scrollController = new ScrollController();
  List<ArticleslistData> articleslist = [];
  var dbHelper = DBHelper();

  @override
  void initState() {
    if (Platform.isAndroid) {
      FirebaseAdMob.instance.initialize(appId: appIdForAndroid);
    } else if (Platform.isIOS) {
      FirebaseAdMob.instance.initialize(appId: appIdForIOS);
    }
    _getOurArticleslist(0);
    dbHelper.countItems().then((val) {
      if (val == 0) {
        _getOurArticleslist(0);
      } else {
        dbHelper.readdb().then((list) {
          print("The Last nid and Pageno is : ");
          print(list[list.length - 1]['nid']);
          print(list[list.length - 1]['pageno']);
          pageno = list[list.length - 1]['pageno'] + 1;
          _getOurArticleslist1(pageno);
        });
      }
    });

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        dbHelper.readdb().then((list) {
          pageno = list[list.length - 1]['pageno'] + 1;
          _getOurArticleslist1(pageno);
        });
        // if we scroll up to bottom of the page
      }
    });
    super.initState();
  }

  @override
  void dispose() {
//    _scrollController.dispose();
    super.dispose();
  }

  _getOurArticleslist1(int pageno) async {
    if (this.mounted) {
      var data = await http.get('$BaseUrl/rest/articles?page=$pageno');
      if (data.contentLength == 5) {
        print('ಲೋಡ್ ಮಾಡಲು ಇನ್ನಷ್ಟು ಲೇಖನಗಳು ಇಲ್ಲ');
      } else {
        if (context != null) {
          Scaffold.of(context).showSnackBar(new SnackBar(
            content: new Text("ಲೋಡ್ ಮಾಡಲಾಗುತ್ತಿದೆ. ದಯವಿಟ್ಟು ನಿರೀಕ್ಷಿಸಿ..."),
            backgroundColor: Colors.deepOrange,
            duration: Duration(milliseconds: 1600),
          ));
        }
      }

      if (data.statusCode == 200) {
        if (this.mounted) {
          setState(() {
            var jsonData = json.decode(utf8.decode(data.bodyBytes));
            for (var e in jsonData) {
              if (e['field_image'] == '[]') {
                e['field_image'] = 'No img';
              }
              ArticleslistData article = ArticleslistData(
                  e['title'],
                  e['nid'],
                  e['field_image'],
                  e['created'],
                  e['uid'],
                  e['totalcount'],
                  pageno);
              articleslist.add(article);
              dbHelper.saveArticle(article);
            }
          });
        }
      } else {
        throw Exception('Failed to load data ');
      }
      if (this.mounted) {
        return articleslist;
      }
    }
    return null();
  }

  _getOurArticleslist(int pageno) async {
    if (this.mounted) {
      var data = await http.get('$BaseUrl/rest/articles?page=$pageno');
      if (data.contentLength == 5) {
        print('ಲೋಡ್ ಮಾಡಲು ಇನ್ನಷ್ಟು ಲೇಖನಗಳು ಇಲ್ಲ');
      } else {
        if (context != null) {
          Scaffold.of(context).showSnackBar(new SnackBar(
            content: new Text("ಲೋಡ್ ಮಾಡಲಾಗುತ್ತಿದೆ. ದಯವಿಟ್ಟು ನಿರೀಕ್ಷಿಸಿ..."),
            backgroundColor: Colors.deepOrange,
            duration: Duration(milliseconds: 1600),
          ));
        }
      }

      if (data.statusCode == 200) {
        var listfromdb;
        if (this.mounted) {
          setState(() {
            var jsonData = json.decode(utf8.decode(data.bodyBytes));
            dbHelper.readdb().then((list) {
              listfromdb = list;
              print('Listfromdb count is');
              print(listfromdb.length);
              if (listfromdb.length == 0) {
                print('\n\nInside listfromdb.length == 0\n\n');
                for (var e in jsonData) {
                  if (e['field_image'].toString() == '[]') {
                    e['field_image'] = 'No img';
                  }
                  ArticleslistData article = ArticleslistData(
                      e['title'],
                      e['nid'],
                      e['field_image'],
                      e['created'],
                      e['uid'],
                      e['totalcount'],
//                      e['body'],
                      pageno);
                  articleslist.add(article);
                  dbHelper.saveArticle(article);
                }
              }
              if (pageno == 0) {
                print('Inside pageno == 0\n\n');
                for (var e = 0; e < jsonData.length; e++) {
                  for (var i = 0; i < listfromdb.length; i++) {
                    print(jsonData[e]['nid'] + ',' + listfromdb[i]['nid']);
                    if (jsonData[e]['nid'] == listfromdb[i]['nid']) {
                      break;
                    } else {
                      if (jsonData[e]['field_image'].toString() == '[]') {
                        jsonData[e]['field_image'] = 'No img';
                      }
                      ArticleslistData article = ArticleslistData(
                          jsonData[e]['title'],
                          jsonData[e]['nid'],
                          jsonData[e]['field_image'],
                          jsonData[e]['created'],
                          jsonData[e]['uid'],
                          jsonData[e]['totalcount'],
                          listfromdb[listfromdb.length - 1]['pageno']);
                      print(article);
                      articleslist.add(article);
                      dbHelper.saveArticle(article);
                      e++;
                    }
                  }
                  break;
                }
              } else if (listfromdb.length != 0) {
                print(' Inside listfromdb.length != 0\n\n');
                for (var e in jsonData) {
                  if (e['field_image'].toString() == '[]') {
                    e['field_image'] = 'No img';
                  }
                  print(e['nid']);
                  ArticleslistData article = ArticleslistData(
                      e['title'],
                      e['nid'],
                      e['field_image'],
                      e['created'],
                      e['uid'],
                      e['totalcount'],
                      pageno);
                  articleslist.add(article);
                  dbHelper.saveArticle(article);
                }
              }
            });
          });
        }
      } else {
        throw Exception('Failed to load data ');
      }
      if (this.mounted) {
        return articleslist;
      }
    }
    return null;
  }

  Future<List<ArticleslistData>> fetchEmployeesFromDatabase() async {
    await new Future.delayed(const Duration(seconds: 1));
    var dbHelper = DBHelper();
    Future<List<ArticleslistData>> articles = dbHelper.getArticles();
    return articles;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: Container(
          padding: new EdgeInsets.all(5.0),
          child: new FutureBuilder<List<ArticleslistData>>(
            future: fetchEmployeesFromDatabase(),
            builder: (context, snapshot) {
              print(snapshot.data);
              if (snapshot.hasData) {
                print('Snapshot has data');
                if (snapshot.data == []) {
                  return new Text(
                      'Poor Connection, Please wait or Try refreshing the content');
                } else {
                  return RefreshIndicator(
                    key: _refreshIndicatorKey,
                    onRefresh: fetchEmployeesFromDatabase,
                    child: ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      controller: _scrollController,
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, index) {
                        var imgUrl = snapshot.data[index].img.toString();
                        imgUrl = imgUrl.replaceAll("\"", "");
                        imgUrl = BaseUrl + imgUrl.toString();
                        print('\n Image Url: $imgUrl \n');
                        var title = snapshot.data[index].title;
                        title = title.replaceAll("&quot;", '"');
                        title = title.replaceAll("&#039;", "'");
                        var views = snapshot.data[index].totalcount;

                        return Container(
                          child: SizedBox.fromSize(
//                            child: GestureDetector(
                            child: new Card(
                              elevation: 2.0,
                              child: Column(
                                children: <Widget>[
                                  GestureDetector(
                                    onTap: () {
                                      print('Tapped : ${snapshot.data[index].nid}');
                                      print(index);
                                      Navigator.push(
                                          context,
                                          new MaterialPageRoute(
                                              builder: (context) => DetailPage(
                                                snapshot.data[index].title,
                                                snapshot.data[index].img,
                                                snapshot.data[index].nid,
                                                snapshot.data[index].uid,
                                              )));
                                    },
                                    child: ListTile(
                                      contentPadding: EdgeInsets.symmetric(
                                          horizontal: 20.0, vertical: 25.0),
                                      leading: Container(
                                        padding: EdgeInsets.only(right: 12.0),
                                        decoration: new BoxDecoration(
                                          border: new Border(
                                              right: new BorderSide(
                                                  width: 1.0, color: Colors.grey)),
                                        ),
                                        child: imgUrl == 'No img'
                                            ? new Image.asset(
                                          'images/placeholder.png',
                                          height: 100,
                                          width: 100,
                                        )
                                            : FadeInImage.assetNetwork(
                                          placeholder: 'images/placeholder.png',
                                          image: imgUrl,
                                          fit: BoxFit.fitWidth,
                                        ),
                                      ),
                                      title: Text(
                                        title,
                                        style: TextStyle(
                                            fontSize: 16,
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold),
                                        overflow: TextOverflow.ellipsis,
                                        maxLines: 2,
                                      ),
                                      subtitle: Text(
                                        'ಲೇಖಕರು : ' + snapshot.data[index].uid,
                                        style: TextStyle(
                                            fontSize: 12,
                                            color: Colors.grey,
                                            fontWeight: FontWeight.bold),
                                        textAlign: TextAlign.left,
                                        overflow: TextOverflow.ellipsis,
                                        maxLines: 1,
                                      ),
                                    ),
                                  ),
                                  Divider(height: .0),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                                    children: <Widget>[
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: <Widget>[
                                          new Icon(Icons.remove_red_eye,size: 14.0),
                                          Center(
                                            child: views == null
                                                ? new Text('')
                                                : new Text('   ${snapshot.data[index].totalcount}  ಓದು'),
                                          )
                                        ],
                                      ),
                                      SizedBox(
                                        height: 40,
                                        child: FlatButton(
                                            child: Row(
                                              children: <Widget>[
//                                              Padding(
//                                                padding: EdgeInsets.all(8.0),
//                                                child:
//                                              ),
                                                Image.asset('images/share-icons.png',scale: 5.0),
                                                new Text('  ಹಂಚಿಕೊಳ್ಳಿ')
                                              ],
                                            ),
                                            onPressed: (){
                                              var nid = articleslist[index].nid;
                                              var url = '$BaseUrl/node/' + nid;
                                              Share.share(url);
                                            }),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  );
                }
              } else if (snapshot.hasError) {
                return new Text(
                  "${snapshot.error}",
                  style: TextStyle(fontSize: 22, color: Colors.black),
                );
              }
              return new Container(
                alignment: AlignmentDirectional.center,
                child: new CircularProgressIndicator(),
              );
            },
          ),
        ));
  }
}

class ArticleslistData {
  final String title;
  final String nid;
  final String img;
  final String created;
  final String uid;
  final String totalcount;
  int pageno;

  ArticleslistData(this.title, this.nid, this.img, this.created, this.uid,
      this.totalcount, this.pageno);
}

dbhelper.dart

import 'dart:async';
import 'dart:io' as io;
import 'package:path/path.dart';
import 'package:models/Article/articleslist.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DBHelper {
  static Database _db;

  Future<Database> get db async {
    if (_db != null) return _db;
    _db = await initDb();
    return _db;
  }

  initDb() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "test.db");
    // await deleteDatabase(path);
    var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return theDb;
  }

  killDb() async{
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "test.db");
    await deleteDatabase(path);
    //initDb();
  }

  void _onCreate(Database db, int version) async {
    // When creating the db, create the table
    await db.execute(
        "CREATE TABLE Employee(title TEXT, nid TEXT PRIMARY KEY, img TEXT,created TEXT, uid TEXT, totalcount TEXT, pageno INTEGER )");
    print("Created tables");
  }

  readdb() async{
    var dbClient = await db;
    return await dbClient.rawQuery('SELECT * FROM Employee');
    //  return dbClient.transaction((txn) async {
    //   return await txn.rawDelete('SELECT * FROM Employee WHERE lastname = ?', ['48670']);
    // });
  }

  cleardb() async{
    var dbClient = await db;
    return dbClient.transaction((txn) async {
      return await txn.rawDelete('DELETE FROM Employee WHERE firstname = ?', ['test']);
    });
  }
  countItems() async{
    var dbClient = await db;
    var count = Sqflite.firstIntValue(await dbClient.rawQuery('SELECT COUNT(*) FROM Employee'));
    return count;
  }

  void saveArticle(ArticleslistData article) async {
    var dbClient = await db;
    await dbClient.transaction((txn) async {
      return await txn.rawInsert(
          'INSERT INTO Employee(title, nid, img, created, uid, totalcount, pageno ) VALUES(' +
              '\'' +
              article.title +
              '\'' +
              ',' +
              '\'' +
              article.nid +
              '\'' +
              ',' +
              '\'' +
              article.img +
              '\'' +
              ',' +
              '\'' +
              article.created +
              '\'' +
              ',' +
              '\'' +
              article.uid +
              '\'' +
              ',' +
              '\'' +
              article.totalcount +
              '\'' +
              ',' +
              '\'' +
              article.pageno.toString() +
              '\'' +
              ')');
    });
  }

  Future<List<ArticleslistData>> getArticles() async {
    var dbClient = await db;
    List<Map> list = await dbClient.rawQuery('SELECT * FROM Employee ORDER BY nid DESC;');
    List<ArticleslistData> articles = new List();
    for (int i = 0; i < list.length; i++) {
      articles.add(new ArticleslistData(list[i]["title"], list[i]["nid"], list[i]["img"], list[i]["created"], list[i]['uid'],list[i]['totalcount'], list[i]['pageno']));
    }
    return articles;
  }
}

1 个答案:

答案 0 :(得分:0)

您万事大吉,但需要setState()告诉flutter重建UI。

如果您不使用状态管理解决方案,请执行此操作。

然后转换为无状态小部件。

onRefresh: () {
SetState() {
fetchEmployeesFromDatabase();
}
}