Flutter: onRefresh回调返回了null。

3

抱歉,我是新手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),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      )
    );
  }
}


你必须在回调函数中返回一个future。 - Pushan Gupta
请问您能展示一下 GetTableList.add(true); 的定义吗? - Augustin R
这里我复制了所有的代码以获取更多细节,请再次检查以上内容。 - Kart Zhai
3个回答

16

只需添加async。

  onRefresh: () async {
    GetTableList.add(true);
  },
onRefresh 是一个 RefreshCallback,而 RefreshCallback 是一个 Future Function()。

如果 GetTableList.add(true) 不返回 Future,则必须添加 async。


1
哦,天啊,你救了我!!它起作用了!!!你能告诉我什么时候应该使用 onRefresh: () async {} 吗? - Kart Zhai

1

提示说onRefresh回调函数必须返回一个Future

看起来你的onRefresh没有返回Future

onRefresh: _refresh

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

希望它有所帮助…


谢谢您,但当我运行_refresh()时,它显示相同的错误。 在调用onRefresh时,抛出了以下断言: onRefresh回调返回了null。 - Kart Zhai

0

您可以尝试使用以下内容:

 Future<bool> refresh() async {

    //your refresh code 

    return true;
  }

你能解释一下你的答案吗?为什么你在硬编码 true? - Greg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接