Flutter:onRefresh回调返回null

时间:2020-01-27 12:45:27

标签: flutter

对不起,我是新手,要尝试学习。我对RefreshIndicator有疑问。

当我尝试拉动它时,出现如下错误:

════════ Exception caught by material library ══════════════════════════════════════════════════════
The following assertion was thrown when calling onRefresh:
The onRefresh callback returned null.

The RefreshIndicator onRefresh callback must return a Future.
════════════════════════════════════════════════════════════════════════════════════════════════════

当前,我正在使用flutter_bloc。这是我的示例代码

TableList_bloc.dart

import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:pos_project_bloc/modal/api.dart';

class ModalTableList {
  final String Table_Number;
  final String Name_Table;

  ModalTableList(
      this.Table_Number,
      this.Name_Table,
      );
}

class tablelistbloc extends Bloc<bool, List<ModalTableList>>{
  @override
  // TODO: implement initialState
  List<ModalTableList> get initialState => [];

  @override
  Stream<List<ModalTableList>> mapEventToState(bool event) async* {
    // TODO: implement mapEventToState

    List<ModalTableList> tablelist =[];
    try {

      final response = await http.get(BaseUrl.GetTableList);
      final data = jsonDecode(response.body);
      if (data.length != 0) {
        data.forEach((api) {
          tablelist.add(
              ModalTableList(
                api['Table_Number'],
                api['Name_Table'],
              )
          );
          print("test"+api['Table_Number'].toString());
        });
        print("Get Table List : sukses");
      } else {
        print('data kosong');
      }
    } catch (e) {
      print("Error GetTableList :");
      print(e);
    }

    yield tablelist;
  }
}

TabeList.dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pos_project_bloc/bloc/TableList_bloc.dart';
import 'package:pos_project_bloc/modal/SharedPreferences.dart';

class TableList extends StatefulWidget {
  @override
  _TableListState createState() => _TableListState();

}

class _TableListState extends State<TableList> {
  @override

  void initState() {
    super.initState();
    BlocProvider.of<tablelistbloc>(context).add(true);
  }

  Widget build(BuildContext context) {

    final GlobalKey<RefreshIndicatorState> refresh = GlobalKey<RefreshIndicatorState>();

    Future<Null> _refresh() async{
      BlocProvider.of<tablelistbloc>(context).add(true);
    }

    return Scaffold(
        appBar: AppBar(
            backgroundColor: Colors.lightBlueAccent,
            title: new Center(
              child: new Text('Available Table',
                  style: new TextStyle(color: Colors.white, fontSize: 15.0)),
            )
        ),
      floatingActionButton: Container(

        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[

            Padding(
              padding: EdgeInsets.all(5.0),
              child: FloatingActionButton.extended(
                heroTag: 1,
                icon: Icon(Icons.refresh),
                label: Text('Refresh Table List'),
                onPressed: () {
                  BlocProvider.of<tablelistbloc>(context).add(true);
                },
              ),
            )
          ],
        ),
      ),

      body: RefreshIndicator(
        onRefresh: (){
          _refresh();
        },
        key: refresh,
        child: BlocBuilder<tablelistbloc,List<ModalTableList>>(

          builder: (context,tablelist)=> ListView.builder(
            itemCount: tablelist.length,
            itemBuilder: (context,index){

              final x = tablelist[index];
              return GestureDetector(
                onTap: (){
                  print("Selected Available Table On Tap : " + x.Table_Number);

                  Shared_Preferences().SaveTableNumber(
                      x.Table_Number
                  );

                  Navigator.pushReplacementNamed(context, '/POS');
                },
                child: Container(
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                            width: 2.0,
                            color: Colors.grey.withOpacity(0.4),
                          ))),
                  padding: EdgeInsets.all(10.0),
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.table_chart,
                        size: 100.0,
                        color: Colors.lightBlueAccent,
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'Table Number :  ' + x.Table_Number,
                            style: TextStyle(
                                fontSize: 20.0,
                                fontWeight: FontWeight.bold,
                                color: Colors.lightBlueAccent),
                          ),

                          Text(
                            'Name :  ' + x.Name_Table,
                            style: TextStyle(
                                fontSize: 20.0,
                                fontWeight: FontWeight.bold,
                                color: Colors.lightBlueAccent),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      )
    );
  }
}

3 个答案:

答案 0 :(得分:6)

只需添加异步。

  onRefresh: () async {
    GetTableList.add(true);
  },

onRefreshRefreshCallback,而RefreshCallback是Future Function()。

因此,如果GetTableList.add(true)不返回Future,则必须添加异步。

答案 1 :(得分:1)

据说onRefresh回调必须返回Future

看来您没有从onRefresh返回Future

onRefresh: _refresh

Future<Null> _refresh() async{
   GetTableList.add(true);
}

希望有帮助。

答案 2 :(得分:0)

您可以使用以下内容:

 Future<bool> refresh() async {

    //your refresh code 

    return true;
  }