Flutter/Dart: 无法在屏幕上刷新RefreshIndicator数据

huangapple go评论99阅读模式
英文:

Flutter/Dart: Not able to refresh RefreshIndicator data on screen

问题

我尝试使用RefreshIndicator从数据库中重新加载数据。在超出滚动时,可以从数据库中读取数据,但不知何故无法刷新屏幕上的数据。我是否遗漏或弄错了什么?

   Future<void> getMTMavailableamount1() async {
        final temp = ModelsPositions().getMasterPositions();
        setState() {
          _futureList = temp;
        }
    }

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: const Text('Master Control'),
              centerTitle: true,
            ),
            body: RefreshIndicator(
              onRefresh: getMTMavailableamount1,
              child: FutureBuilder<List<dynamic>>(
                future: _futureList,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    List<dynamic> positions = snapshot.data ?? [];
                    return ListView.builder(
                      itemCount: positions.length,
                      itemBuilder: (context, index) {
                        String custID = positions[index][0];
                        String custName = positions[index][1];
                        double m2m = double.parse(positions[index][2]);
                        double available = double.parse(positions[index][3]);
英文:

I'm trying to reload data from DB with RefreshIndicator. Upon over-scroll, Able to read data from DB but somehow not able to refresh the data on the screen. Did i miss/mess up anything?

 Future&lt;void&gt; getMTMavailableamount1() async {
    final temp = ModelsPositions().getMasterPositions();
    setState() {
      _futureList = temp;
    }
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(&#39;Master Control&#39;),
          centerTitle: true,
        ),
        body: RefreshIndicator(
          onRefresh: getMTMavailableamount1,
          child: FutureBuilder&lt;List&lt;dynamic&gt;&gt;(
            future: _futureList,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List&lt;dynamic&gt; positions = snapshot.data ?? [];
                return ListView.builder(
                  itemCount: positions.length,
                  itemBuilder: (context, index) {
                    String custID = positions[index][0];
                    String custName = positions[index][1];
                    double m2m = double.parse(positions[index][2]);
                    double available = double.parse(positions[index][3]);

答案1

得分: 1

Introduce new variable called uniqueKey and that should be ValueKey with the value of future.

late ValueKey<Future> uniqueKey;
Future<void> getMTMavailableamount1() async {
    final temp = ModelsPositions().getMasterPositions();
    setState(() {
      _futureList = temp;
      uniqueKey = ValueKey(_futureList);
    });
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Master Control'),
          centerTitle: true,
        ),
        body: RefreshIndicator(
          onRefresh: getMTMavailableamount1,
          child: FutureBuilder<List<dynamic>>(
            future: _futureList,
            key: uniqueKey,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<dynamic> positions = snapshot.data ?? [];
                return ListView.builder(
                  itemCount: positions.length,
                  itemBuilder: (context, index) {
                    String custID = positions[index][0];
                    String custName = positions[index][1];
                    double m2m = double.parse(positions[index][2]);
                    double available = double.parse(positions[index][3]);

Make sure you initiated uniqueKey at initState().


  @override
  void initState() {
    super.initState();
    _futureList = ModelsPositions().getMasterPositions();
     uniqueKey = ValueKey<Future>(_futureList);
  }

Edited

You misused setState. your code creates a new inline function instead of calling setState of State. setState looks like as following.

setState(() {
      _futureList = temp;
      uniqueKey = ValueKey(_futureList);
    });
英文:

Introduce new variable called uniqueKey and that should be ValueKey with the value of future.

late ValueKey&lt;Future&gt; uniqueKey;
Future&lt;void&gt; getMTMavailableamount1() async {
    final temp = ModelsPositions().getMasterPositions();
    setState(() {
      _futureList = temp;
      uniqueKey = ValueKey(_futureList);
    });
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(&#39;Master Control&#39;),
          centerTitle: true,
        ),
        body: RefreshIndicator(
          onRefresh: getMTMavailableamount1,
          child: FutureBuilder&lt;List&lt;dynamic&gt;&gt;(
            future: _futureList,
            key: uniqueKey,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List&lt;dynamic&gt; positions = snapshot.data ?? [];
                return ListView.builder(
                  itemCount: positions.length,
                  itemBuilder: (context, index) {
                    String custID = positions[index][0];
                    String custName = positions[index][1];
                    double m2m = double.parse(positions[index][2]);
                    double available = double.parse(positions[index][3]);

Make sure you initiated uniqueKey at initState().


  @override
  void initState() {
    super.initState();
    _futureList = ModelsPositions().getMasterPositions();
     uniqueKey = ValueKey&lt;Future&gt;(_futureList);
  }

Edited

You misused setState. your code creates a new inline function instead of calling setState of State. setState looks like as following.

setState(() {
      _futureList = temp;
      uniqueKey = ValueKey(_futureList);
    });

答案2

得分: 0

import 'dart:async';
import 'package:e2/pages/authorize.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:e2/Models/model_positions.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class MasterControl extends StatefulWidget {
  const MasterControl({super.key});

  @override
  State<MasterControl> createState() => _MasterControlState();
}

class _MasterControlState extends State<MasterControl> {
  List<dynamic> _selectedItems = [];
  // List<MasterPositions> positions = [];
  late Future<List<dynamic>> _futureList;

  @override
  void initState() {
    super.initState();
    _futureList = ModelsPositions().getMasterPositions();
    uniqueKey = ValueKey<Future>(_futureList);
  }

  late ValueKey<Future> uniqueKey;
  Future<void> getMTMavailableamount1() async {
    final response = await http.post(
      Uri.parse('https://jhkmmy7zhx2dj2yag74j7p5k2e0fyqnj.lambda-url.ap-south-1.on.aws/'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
    );
    final temp = ModelsPositions().getMasterPositions();
    setState() {
      _futureList = temp;
      uniqueKey = ValueKey(_futureList);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Master Control'),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        onRefresh: getMTMavailableamount1,
        child: FutureBuilder<List<dynamic>>(
          future: _futureList,
          key: uniqueKey,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              List<dynamic> positions = snapshot.data ?? [];
              return ListView.builder(
                itemCount: positions.length,
                itemBuilder: (context, index) {
                  String custID = positions[index][0];
                  String custName = positions[index][1];
                  double m2m = double.parse(positions[index][2]);
                  double available = double.parse(positions[index][3]);
                  // String symbol = positions[index][4];

                  return Card(
                    child: Row(children: [
                      Checkbox(
                        value: _selectedItems.contains(positions[index]),
                        onChanged: (value) {
                          setState(() {
                            if (value == null) {
                              return;
                            }
                            if (value) {
                              _selectedItems.add(positions[index]);
                            } else {
                              _selectedItems.removeWhere((item) => item == positions[index]);
                            }
                          });
                        },
                      ),
                      Flexible(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            const SizedBox(height: 2),
                            Text(custID),
                            const SizedBox(height: 2),
                            Text(custName),
                            const SizedBox(height: 2),
                          ],
                        ),
                      ),
                      Flexible(
                        // fit: FlexFit.tight,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            const SizedBox(height: 3),
                            Text(
                              'MTM       : $m2m',
                              softWrap: false,
                              style: TextStyle(
                                fontFamily: 'Roboto',
                                color: m2m > 0.0
                                    ? const Color.fromARGB(255, 11, 180, 16)
                                    : Colors.red[600],
                              ),
                            ),
                            const SizedBox(height: 5),
                            Text(
                              'Available : $available',
                              softWrap: false,
                              style: TextStyle(
                                fontFamily: 'Roboto',
                                color: available > 0.0
                                    ? const Color.fromARGB(255, 11, 180, 16)
                                    : Colors.red[600],
                              ),
                            ),
                            const SizedBox(height: 5),
                          ],
                        ),
                      ),
                    ]),
                  );
                },
              );
            } else if (snapshot.hasError) {
              return const Center(child: Text('Failed to fetch Positions Summary'));
            }
            return const Center(child: CircularProgressIndicator());
          },
        ),
      ),
    );
  }
}

class LambdaResponse {
  late int statusCode;
  late String msg;

  LambdaResponse({required this.statusCode, required this.msg});

  factory LambdaResponse.fromJson(String response) {
    print('here1');
    print(response);
    return LambdaResponse(
      statusCode: 1,
      msg: response,
    );
  }
}

这是您提供的Dart代码的翻译版本。如您所要求,我已经去掉了代码部分的翻译。如果您有任何其他问题或需要进一步的帮助,请随时告诉我。

英文:
import &#39;dart:async&#39;;
import &#39;package:e2/pages/authorize.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:fluttertoast/fluttertoast.dart&#39;;
import &#39;package:e2/Models/model_positions.dart&#39;;
import &#39;package:http/http.dart&#39; as http;
import &#39;dart:convert&#39;;
class MasterControl extends StatefulWidget {
const MasterControl({super.key});
@override
State&lt;MasterControl&gt; createState() =&gt; _MasterControlState();
}
class _MasterControlState extends State&lt;MasterControl&gt; {
List&lt;dynamic&gt; _selectedItems = [];
//List&lt;MasterPositions&gt; positions = [];
late Future&lt;List&lt;dynamic&gt;&gt; _futureList;
@override
void initState() {
super.initState();
_futureList = ModelsPositions().getMasterPositions();
uniqueKey = ValueKey&lt;Future&gt;(_futureList);
}
late ValueKey&lt;Future&gt; uniqueKey;
Future&lt;void&gt; getMTMavailableamount1() async {
final response = await http.post(
Uri.parse(
&#39;https://jhkmmy7zhx2dj2yag74j7p5k2e0fyqnj.lambda-url.ap-south-1.on.aws/&#39;),
headers: &lt;String, String&gt;{
&#39;Content-Type&#39;: &#39;application/json; charset=UTF-8&#39;,
},
);
final temp = ModelsPositions().getMasterPositions();
setState() {
_futureList = temp;
uniqueKey = ValueKey(_futureList);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(&#39;Master Control&#39;),
centerTitle: true,
),
body: RefreshIndicator(
onRefresh: getMTMavailableamount1,
child: FutureBuilder&lt;List&lt;dynamic&gt;&gt;(
future: _futureList,
key: uniqueKey,
builder: (context, snapshot) {
if (snapshot.hasData) {
List&lt;dynamic&gt; positions = snapshot.data ?? [];
return ListView.builder(
itemCount: positions.length,
itemBuilder: (context, index) {
String custID = positions[index][0];
String custName = positions[index][1];
double m2m = double.parse(positions[index][2]);
double available = double.parse(positions[index][3]);
//String symbol = positions[index][4];
return Card(
child: Row(children: [
Checkbox(
value: _selectedItems.contains(positions[index]),
onChanged: (value) {
setState(() {
if (value == null) {
return;
}
if (value) {
_selectedItems.add(positions[index]);
} else {
_selectedItems.removeWhere(
(item) =&gt; item == positions[index]);
}
});
},
),
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 2),
Text(custID),
const SizedBox(height: 2),
Text(custName),
const SizedBox(height: 2),
],
),
),
Flexible(
//fit: FlexFit.tight,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 3),
Text(
&#39;MTM       : $m2m&#39;,
softWrap: false,
style: TextStyle(
fontFamily: &#39;Roboto&#39;,
color: m2m &gt; 0.0
? const Color.fromARGB(255, 11, 180, 16)
: Colors.red[600]),
),
const SizedBox(height: 5),
Text(
&#39;Available : $available&#39;,
softWrap: false,
style: TextStyle(
fontFamily: &#39;Roboto&#39;,
color: available &gt; 0.0
? const Color.fromARGB(255, 11, 180, 16)
: Colors.red[600]),
),
const SizedBox(height: 5),
],
),
),
]));
},
);
} else if (snapshot.hasError) {
return const Center(
child: Text(&#39;Failed to fetch Positions Summary&#39;));
}
return const Center(child: CircularProgressIndicator());
},
),
),);
}
}
class LambdaResponse {
late int statusCode;
late String msg;
LambdaResponse({required this.statusCode, required this.msg});
factory LambdaResponse.fromJson(String response) {
print(&#39;here1&#39;);
print(response);
return LambdaResponse(
statusCode: 1,
msg: response,
);
}
}

huangapple
  • 本文由 发表于 2023年3月9日 18:04:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683068.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定