简体   繁体   中英

Getting an error while trying to get data from sqlite database in flutter app

I'm trying to get data from sqlite database using sqflite and insert it in list_view. Anything seems fine but when I add something to the database and try to get the data and put it in a list view in home.dart file, I keep getting an error.

Below is the home.dart file. This is where I'm trying to get data from database and make a list view. The error occurs on this file.

import 'package:com.example.simple_app/models/person.dart';
import 'package:com.example.simple_app/utils/db_helper.dart';
import 'package:flutter/material.dart';
import 'package:com.example.simple_app/common_widgets/appbar.dart';
import 'package:com.example.simple_app/common_widgets/drawer.dart';
import 'dart:async';
import 'package:sqflite/sqflite.dart';

Future<List<Person>> getPersonsFromDB() async {
  var dbHelper = DBHelper();
  Future<List<Person>> persons = dbHelper.getPersons();
  return persons;
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}
class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  final List<Widget> _children = [];
  static const TextStyle moneyLendingAction =
      TextStyle(color: Colors.white, fontSize: 20);
  final controller_name = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appbar(context, 'Simple App', 'other data'),
      body: new Container(
        padding: EdgeInsets.all(16.0),
        child: FutureBuilder<List<Person>>(
            future: getPersonsFromDB(),
            builder: (context, snapshot) {
                print(snapshot.data);

              if (snapshot.data != null) {
                if (snapshot.hasData) {
                  return ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, index) {
                        return new Row(
                          children: <Widget>[
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Container(
                                    padding: const EdgeInsets.only(
                                      bottom: 8.0,
                                    ),
                                    child: Text(
                                      snapshot.data[index].name,
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        );
                      });
                }
              }
              // show loading
              // return new Container(
              //   alignment: AlignmentDirectional.center,
              //   child: new CircularProgressIndicator(),
              // );
            }),
      ),
    );
  }
    setState(() {
      _currentIndex = index;
    });
  }
}

Below is the db_helper.dart file.

import 'dart:async';
import 'dart:io' as io;
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:com.example.simple_app/models/person.dart';
import 'package:path/path.dart';

class DBHelper {
  static Database db_instance;

  Future<Database> get db async {
    if (db_instance == null) db_instance = await initDB();
    return db_instance;
  }

  initDB() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'demo2.db');
    var db = await openDatabase(path, version: 1, onCreate: onCreateFunc);
    return db;
  }

  void onCreateFunc(Database db, int version) async {
    // create table
    await db.execute(
        'CREATE TABLE person(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, created DATETIME, updated DATETIME);');
  }

  /**
   * crud functions
   */

  Future<List<Person>> getPersons() async {
    var db_connection = await db;
    List<Map> list = await db_connection.rawQuery('SELECT * FROM person');
    List<Person> persons = new List();
    for (int i = 0; i < list.length; i++) {
      Person person = new Person();
      person.id = list[i]['id'];
      person.name = list[i]['name'];
      person.created = list[i]['created'];
      person.updated = list[i]['updated'];

      persons.add(person);
    }
    return persons;
  }

  // add new person
  void addNewPerson(Person person) async {
    var db_connection = await db;
    String query = """
        INSERT INTO person(name,created,updated) VALUES('${person.name}','${person.created}', '${person.updated}')
        """;
    await db_connection.transaction((transaction) async {
      return await transaction.rawInsert(query);
    });
  }

  // update person
  void updatePerson(Person person) async {
    var db_connection = await db;
    String query = """
        UPDATE person SET name='${person.name}',created='${person.created}',updated='${person.updated}' WHERE id=${person.id}
        """;
    await db_connection.transaction((transaction) async {
      return await transaction.rawQuery(query);
    });
  }

  // delete person
  void deletePerson(Person person) async {
    var db_connection = await db;
    String query = """
        DELETE FROM person WHERE id=${person.id}
        """;
    await db_connection.transaction((transaction) async {
      return await transaction.rawQuery(query);
    });
  }
}

Below is the error log I'm getting in the debug console.

I/flutter (12326): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (12326): The following assertion was thrown building FutureBuilder<List<Person>>(dirty, state:
I/flutter (12326): _FutureBuilderState<List<Person>>#caa58):
I/flutter (12326): A build function returned null.
I/flutter (12326): The offending widget is:
I/flutter (12326):   FutureBuilder<List<Person>>
I/flutter (12326): Build functions must never return null.
I/flutter (12326): To return an empty space that causes the building widget to fill available room, return
I/flutter (12326): "Container()". To return an empty space that takes as little room as possible, return
// and the logs go on and on below...

What I don't understand is anything seems fine but when I try to get data from sqlite database and list the data in Home Page file I keep getting an error. This may be a simple problem but because I'm new to flutter I'm failing to figure this out.

What I want is to be able to get the data from the database and put it in a list view in Home Page without getting any error. Thank you, Posted with love.

As stated, Build functions must never return null . Simply uncomment the code you have commented which will be called before the future completes:

// show loading
return new Container(
  alignment: AlignmentDirectional.center,
  child: new CircularProgressIndicator(),
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM