NoSuchMethodError: getter length was called on null

You can copy paste run full code below
Step 1: Move out ListView.separated from RaisedButton
Step 2: Move out List<Breeds> allBreedsList from build
Step 3: MyApp use StatefulWidget and call setState(() {}); after _pullAllbreed();

onPressed: () {
        print("Yeah, it works!");
        _pullAllbreed();
        setState(() {});
      }),

working demo

enter image description here

full code

import 'package:flutter/material.dart';

class DatabaseHelper {
  Future<List<Breeds>> breedList() {
    return Future.value(
        [Breeds(name: "a"), Breeds(name: "b"), Breeds(name: "c")]);
  }
}

class Breeds {
  String name;
  Breeds({this.name});
}

void main() => runApp(MyApp());

final dbHelper = DatabaseHelper();

List<Breeds> allBreedsList = [];

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'My 1st App',
        home: Scaffold(
            appBar: AppBar(
              title: Text('Pets, Pets, Pets'),
            ),
            body: Center(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                  RaisedButton(
                      child: Text(
                        'query',
                        style: TextStyle(fontSize: 20),
                      ),
                      onPressed: () {
                        print("Yeah, it works!");
                        _pullAllbreed();
                        setState(() {});
                      }),
                  Expanded(
                      child: ListView.separated(
                    itemBuilder: (context, index) {
                      return ListTile(
                        leading: Text("${allBreedsList[index]}"),
                        title: Text("${allBreedsList[index].name}"),
                      );
                    },
                    separatorBuilder: (context, index) => Divider(),
                    itemCount: allBreedsList.length,
                  ))
                ]))));
  }
}

void _pullAllbreed() async {
  allBreedsList = await dbHelper.breedList();
  print('querying all breeds now, please stand by');
  allBreedsList.forEach((row) => print(row));
  int breedCount = allBreedsList.length;
  print(breedCount);
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top