Flutter有状态的Widget State未初始化

5
我正在使用Flutter制作一款命令和控制应用程序,并遇到了一个奇怪的问题。应用程序的主状态页面显示了一个有状态小部件列表,每个小部件都拥有一个WebSocket连接,该连接从连接的机器人平台中流式传输状态数据。当机器人自身被硬编码时,这种方式很有效。然而,现在我正在通过条形码扫描动态添加它们,只有第一个小部件显示状态。
进一步调查发现,这是由于仅为列表中的第一个小部件创建了状态。随后添加的小部件成功构建,但未获得状态。这意味着除第一个添加的小部件外,createState未被调用。我检查了小部件是否确实被添加到列表中,并且它们各自具有唯一的哈希代码。此外,IOWebSocketChannel具有唯一的哈希代码,所有小部件数据对于列表中的不同元素都是正确且唯一的。
有任何想法是什么导致了这个问题?
HomePageState的代码:
class HomePageState extends State<HomePage> {
  String submittedString = "";
  StateContainerState container;
  List<RobotSummary> robotList = [];
  List<String> robotIps = [];
  final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();

  void addRobotToList(String ipAddress) {
    var channel = new IOWebSocketChannel.connect('ws://' + container.slsData.slsIpAddress + ':' + container.slsData.wsPort);
    channel.sink.add("http://" + ipAddress);
    var newConnection = new RobotSummary(key: new UniqueKey(), channel: channel, ipAddress: ipAddress, state: -1, fullAddress: 'http://' + container.slsData.slsIpAddress + ':' + container.slsData.wsPort,);
    scaffoldKey.currentState.showSnackBar(new SnackBar(
      content: new Text("Adding robot..."), duration: Duration(seconds: 2),));
    setState(() {
      robotList.add(newConnection);
      robotIps.add(ipAddress);
      submittedString = ipAddress;
    });
  }

  void _onSubmit(String val) {

    // Determine the scan data that was entered
    if(Validator.isIP(val)) {
      if(ModalRoute.of(context).settings.name == '/') {
        if (!robotIps.contains(val)) {
          addRobotToList(val);
        }
        else {
          scaffoldKey.currentState.showSnackBar(new SnackBar(
            content: new Text("Robot already added..."), duration: Duration(seconds: 5),));
        }
      }
      else {
        setState(() {
          _showSnackbar("Robot scanned. Go to page?", '/');
        });
      }
    }
    else if(Validator.isSlotId(val)) {
      setState(() {
        _showSnackbar("Slot scanned. Go to page?", '/slots');
      });
    }
    else if(Validator.isUPC(val)) {
      setState(() {
        _showSnackbar("Product scanned. Go to page?", '/products');
      });
    }
    else if (Validator.isToteId(val)) {

    }
  }

  @override
  Widget build(BuildContext context) {
    container = StateContainer.of(context);
    return new Scaffold (
      key: scaffoldKey,
      drawer: Drawer(
        child: CategoryRoute(),
      ),
      appBar: AppBar(
        title: Text(widget.topText),  
      ),
      bottomNavigationBar: BottomAppBar(
        child: new Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            IconButton(icon: Icon(Icons.camera_alt), onPressed: scan,),
            IconButton(icon: Icon(Icons.search), onPressed: _showModalSheet,),
          ],
        ),
      ),
      body: robotList.length > 0 ? ListView(children: robotList) : Center(child: Text("Please scan a robot.", style: TextStyle(fontSize: 24.0, color: Colors.blue),),),
    );
  }

  void _showModalSheet() {
    showModalBottomSheet(
        context: context,
        builder: (builder) {
          return _searchBar(context);
        });
  }

  void _showSnackbar(String message, String route) {
    scaffoldKey.currentState.showSnackBar(new SnackBar(
      content: new Text(message),
      action: SnackBarAction(
        label: 'Go?', 
        onPressed: () {
          if (route == '/') {
            Navigator.popUntil(context,ModalRoute.withName('/'));
          }
          else {
            Navigator.of(context).pushNamed(route); 
          }
        },),
      duration: Duration(seconds: 5),));
  }

  Widget _searchBar(BuildContext context) {
    return new Scaffold(
      body: Container(
      height: 75.0,
      color: iam_blue,
      child: Center(
      child: TextField(
        style: TextStyle (color: Colors.white, fontSize: 18.0),
        autofocus: true,
        keyboardType: TextInputType.number,
        onSubmitted: (String submittedStr) {
          Navigator.pop(context);
          _onSubmit(submittedStr);
        },
        decoration: new InputDecoration(
        border: InputBorder.none,
        hintText: 'Scan a tote, robot, UPC, or slot',
        hintStyle: TextStyle(color: Colors.white70),
        icon: const Icon(Icons.search, color: Colors.white70,)),
      ),
    )));
  }

  Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      setState(() => this._onSubmit(barcode));
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          print('The user did not grant the camera permission!');
        });
      } else {
        setState(() => print('Unknown error: $e'));
      }
    } on FormatException{
      setState(() => print('null (User returned using the "back"-button before scanning anything. Result)'));
    } catch (e) {
      setState(() => print('Unknown error: $e'));
    }
  }
}

RobotSummary类的代码片段:

import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import 'package:test_app/genericStateSummary_static.dart';
import 'dart:convert';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:test_app/StateDecodeJsonFull.dart';
import 'dart:async';
import 'package:test_app/dataValidation.dart';

class RobotSummary extends StatefulWidget {
  final String ipAddress;
  final String _port = '5000';
  final int state;
  final String fullAddress;
  final WebSocketChannel channel;

  RobotSummary({
    Key key,
    @required this.ipAddress,
    @required this.channel,
    this.state = -1,
    this.fullAddress = "http://10.1.10.200:5000",
  }) :  assert(Validator.isIP(ipAddress)),
        super(key: key);

  @override
  _RobotSummaryState createState() => new _RobotSummaryState();
}

class _RobotSummaryState extends State<RobotSummary> {
  StreamController<StateDecodeJsonFull> streamController;

  @override
  void initState() {
    super.initState();
    streamController = StreamController.broadcast();
  }

  @override
  Widget build(BuildContext context) {

    return new Padding(
      padding: const EdgeInsets.all(20.0),
      child: new StreamBuilder(
        stream: widget.channel.stream,
        builder: (context, snapshot) {
          //streamController.sink.add('{"autonomyControllerState" : 3,  "pickCurrentListName" : "69152", "plannerExecutionProgress" : 82,   "pickUpcCode" : "00814638", "robotName" : "Adam"}');
          return getStateWidget(snapshot);
        },
      ),
    );
  }

  @override
  void dispose() {
    streamController.sink.close();
    super.dispose();
  }
}

如果将Scaffold body更改为 ListView(children: roboList),它会工作吗?或者如果在setState内部重新创建列表,创建一个新的列表并从旧列表中addAll呢? - Jacob Phillips
我尝试了这两个方法。不幸的是,它们都没有起作用。不过我喜欢你的想法,也许构建器会将子项视为不同,并触发状态的构建/重建流程。我还使用第一个选项来清理我的代码并摆脱了一个有点无用的类(RobotList)。已更新上面的代码以反映这一点。 - user8067251
2个回答

1
基于 Jacob 在他的初始评论中所说的内容,我想出了一个可行且结合了他建议的解决方案。他提出的代码解决方案无法实现(请参见我的评论),但也许可以尝试进行修改以采用其中的元素。对于我现在使用的解决方案,HomePageState 的构建器调用如下:
Widget build(BuildContext context) {
    List<RobotSummary> tempList = [];
    if (robotList.length > 0) {
      tempList.addAll(robotList);
    }
    container = StateContainer.of(context);
    return new Scaffold (
      key: scaffoldKey,
      drawer: Drawer(
        child: CategoryRoute(),
      ),
      appBar: AppBar(
        title: Text(widget.topText),  
      ),
      bottomNavigationBar: BottomAppBar(
        child: new Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            IconButton(icon: Icon(Icons.camera_alt), onPressed: scan,),
            IconButton(icon: Icon(Icons.search), onPressed: _showModalSheet,),
          ],
        ),
      ),
      body: robotList.length > 0 ? ListView(children: tempList) : Center(child: Text("Please scan a robot.", style: TextStyle(fontSize: 24.0, color: iam_blue),),),
    );
  }

0
问题在于你在build调用之间一直持有StatefulWidget,所以它们的状态始终相同。尝试将RobotSummary的业务逻辑与视图逻辑分离。类似这样的方式:
class RobotSummary {
  final String ipAddress;
  final String _port = '5000';
  final int state;
  final String fullAddress;
  final WebSocketChannel channel;
  StreamController<StateDecodeJsonFull> streamController;

  RobotSummary({
    @required this.ipAddress,
    @required this.channel,
    this.state = -1,
    this.fullAddress = "http://10.1.10.200:5000",
  }) :  assert(Validator.isIP(ipAddress));

  void init() => streamController = StreamController.broadcast();
  void dispose() => streamController.sink.close();
}

然后在你的 Scaffold body 中:

...

body: ListView.builder(itemCount: robotList.length, itemBuilder: _buildItem)

...

Widget _buildItem(BuildContext context, int index) {
  return new Padding(
      padding: const EdgeInsets.all(20.0),
      child: new StreamBuilder(
        stream: robotList[index].channel.stream,
        builder: (context, snapshot) {
          //streamController.sink.add('{"autonomyControllerState" : 3,  "pickCurrentListName" : "69152", "plannerExecutionProgress" : 82,   "pickUpcCode" : "00814638", "robotName" : "Adam"}');
          return getStateWidget(snapshot); // not sure how to change this.
        },
      ),
    );
}

问题在于RobotSummary不是一个列表,而是一个列表元素。主页正文中的显示是RobotSummary小部件的ListView。 - user8067251
是的,ListView通过调用_buildItem函数填充每个RobotSummary对象。 - Jacob Phillips

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