【问题标题】:How to return a spreadsheet which has list of widgets from a build in flutter?如何从flutter中返回包含小部件列表的电子表格?
【发布时间】:2021-08-07 06:49:15
【问题描述】:

我想从小部件的构建方法返回一个包含在电子表格运算符中的小部件(ElevatedButton(s))列表,但构建需要一个适当的小部件,并且 IDE 在电子表格运算符上抛出“预期标识符”的错误”。

接收类:-

import 'package:flutter/material.dart';

import 'question.dart';
import 'answer.dart';

class Quiz extends StatelessWidget {
  final List questionList;
  final int questionIndex;
  final changeQuestion;
  Quiz(this.questionList, this.questionIndex, this.changeQuestion);
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Question(questionList, questionIndex),
        Answer(questionList, questionIndex, changeQuestion),
      ],
    );
  }
}

^^^这里的答案是接收发送类的参数。

返回的类:-

import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final List questionList;
  final int questionIndex;
  final Function changeQuestion;
  Answer(this.questionList, this.questionIndex, this.changeQuestion);
  @override
  Widget build(BuildContext context) {
    return ...(questionList[questionIndex]["answer"] as List<Map<String, Object>>)
            .map((e) {
          return ElevatedButton(
            onPressed: () => changeQuestion(e["point"] as int),
            child: Text(e["text"] as String),
          );
        },);
  }
}

电子表格运算符(...)说“需要一个标识符”。

【问题讨论】:

  • return Row(children: [...your code]);

标签: flutter dart


【解决方案1】:

小部件的构建方法期望返回单个小部件。您正在尝试返回小部件列表。

一种解决方案是将您的答案小部件包装在Column 中。列小部件需要一个小部件列表。你可以这样使用它:

import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final List questionList;
  final int questionIndex;
  final Function changeQuestion;
  Answer(this.questionList, this.questionIndex, this.changeQuestion);
  @override
  Widget build(BuildContext context) {
    return Colunm(
       children: (questionList[questionIndex]["answer"] as List<Map<String, Object>>)
            .map((e) {
          return ElevatedButton(
            onPressed: () => changeQuestion(e["point"] as int),
            child: Text(e["text"] as String),
         );
       }),
    );
  }
}

如果您希望按钮水平堆叠,您可以使用Row 而不是列,或者更好的是您可以使用WrapFor which you can see more detail here

扩展运算符

spread operator 用于将一个列表插入另一个列表。你可以这样使用它:

var list = [1, 2, 3];
var list2 = [0, ...list];
assert(list2.length == 4);

它可以在您的小部件树中使用。如果您有一个 Column(或其他接受多个子元素的小部件)并将其与 if 运算符结合使用,则它特别有用:

Column(
  children: [
    Text('Some widget'),

    // These three widgets are only added if the condition is true
    if(someCondition) ...[ 
      Spacer(),
      Text('Multiple added wigets'),
      Spacer(),
    ],

    Text('After widget'),
  ]
)

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    相关资源
    最近更新 更多