Home > Software design >  Background text in a Flutter list
Background text in a Flutter list

Time:02-21

I am looking for a quick alternative to indicate that the list is blank.

Something quick and easy occurs to me that would be to show a text that always says that it is blank... and when the list has an element, said element is placed above the text making it hide.

That is, the text will be behind the list.

Any solution?

My example code is this: https://pub.dev/packages/flutter_blue/example

             StreamBuilder<List<ScanResult>>(
                stream: FlutterBlue.instance.scanResults,
                initialData: [],
                builder: (c, snapshot) => Column(
                  children: snapshot.data!
                      .where((r) => r.device.name != '')
                      .map(
                        (r) => ScanResultTile(
                          result: r,
                          onTap: () => Navigator.of(context)
                              .push(MaterialPageRoute(builder: (context) {
                            r.device.connect();
                            return DeviceScreen(device: r.device);
                          })),
                        ),
                      )
                      .toList(),
                ),
              ),

CodePudding user response:

Here's a way to do this by adding an optional progress loading, if you prefer you can remove it. If your list has items, it will be built, otherwise the text will be displayed.

StreamBuilder<List<ScanResult>>(
  stream: FlutterBlue.instance.scanResults,
  initialData: [],
  builder: (c, snapshot) {
    if(!snapshot.hasData){
      return CircularProgressIndicator(); 
    }
    final listItems = snapshot.data!.where((r) => r.device.name != '').toList();
    return  listItems.isNotEmpty ? Column(
        children: snapshot.data!
            .map(
              (r) => ScanResultTile(
                result: r,
                onTap: () => Navigator.of(context)
                    .push(MaterialPageRoute(builder: (context) {
                  r.device.connect();
                  return DeviceScreen(device: r.device);
                })),
              ),
            )
            .toList(),
        ): const Text("Has no items")
      },
),

CodePudding user response:

Use if-else to check whether list is empty.

  StreamBuilder<List<ScanResult>>(
          stream: FlutterBlue.instance.scanResults,
          initialData: [],
          builder: (c, snapshot) {
        if (snapshot.data!.isEmpty) {
            return NoItem(); // show blank text
        } else {
           return Column(...);
        }
    });
  • Related