简体   繁体   English

如何在 Flutter 中使用 widget/s 从文件中读取文本并将它们显示为列表?

[英]How can I read text from files and display them as list using widget/s in Flutter?

may I ask a way how to make this work.我可以问一种如何使这项工作的方法。

I have a text file named questions.txt .我有一个名为questions.txt的文本文件。

This file contains the following questions:该文件包含以下问题:

  1. How old are you?你几岁?
  2. Where do you live?你住在哪里?
  3. What is your age?你几岁?

I want to load these questions from the file, and render them as a list in Flutter.我想从文件中加载这些问题,并在 Flutter 中将它们呈现为列表。

questionnaires.dart问卷.dart

import 'package:flutter/material.dart';
class Questionnaires extends StatefulWidget {
    @override
    _QuestionnairesState createState() => _QuestionnairesState();
}

class _QuestionnairesState extends State<Questionnaires> {
    String q1 = "";
    String q2 = "";
    String q3 = "";
    @override
    Widget build(BuildContext context) {
        return SafeArea(
            child: Scaffold(
            resizeToAvoidBottomInset: false,
                body: Center(
                    child: Column(
                        children: <Widget>[
                            Text(q1),
                            Text(q2),
                            Text(q3)
                        ],
                    ),
                ),
            ),
        );
    }
}

You can start with the most basic way of retrieving the questions from a .txt file using rootBundle.loadString , then display it using a ListView widget.您可以从使用rootBundle.loadString.txt文件中检索问题的最基本方法开始,然后使用ListView小部件显示它。

main.dart main.dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Questions',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyAppScreen(),
    );
  }
}

class MyAppScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppScreenState();
  }
}

class MyAppScreenState extends State<MyAppScreen> {
  List<String> _questions = [];

  Future<List<String>> _loadQuestions() async {
    List<String> questions = [];
    await rootBundle.loadString('path/to/questions.txt').then((q) {
      for (String i in LineSplitter().convert(q)) {
        questions.add(i);
      }
    });
    return questions;
  }

  @override
  void initState() {
    _setup();
    super.initState();
  }

  _setup() async {
    // Retrieve the questions (Processed in the background)
    List<String> questions = await _loadQuestions();

    // Notify the UI and display the questions
    setState(() {
      _questions = questions;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Flutter Questions")),
      body: Center(
        child: Container(
          child: ListView.builder(
            itemCount: _questions.length,
            itemBuilder: (context, index) {
              return Text(_questions[index]);
            },
          ),
        ),
      ),
    );
  }
}

And here are the sample list of questions.这是问题的示例列表。

questions.txt问题.txt

"How old are you?"
"Where do you live?"
"What is your age?"

In the example code above, you are parsing the text file line by line , please see LineSplitter .在上面的示例代码中,您正在逐行解析文本文件,请参阅LineSplitter This is good for small and sample projects while you're testing out Flutter.这对于测试 Flutter 的小型和示例项目很有用。 But you should be able to update this implementation by following the official docs of Flutter, on how you can read from and write on files.但是您应该能够通过遵循 Flutter 的官方文档来更新此实现,了解如何读取和写入文件。

Furthermore, if you want to go big with your Flutter project, you should look into ways on how you can host your questions online, eg.此外,如果您想扩大 Flutter 项目,您应该研究如何在线托管您的问题,例如。 served via REST APIs, then retrieve it using the http plugin for Flutter.通过 REST API 提供服务,然后使用 Flutter 的http插件检索它。

More on:更多关于:

Output:输出:

图像 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 显示从 sharedprefrence 到文本小部件 flutter 的数据列表? - Display list of datas from sharedprefrence to text widget flutter? 如何遍历 map 列表并在 flutter 列表视图中显示文本小部件? - How to iterate through list of map and display Text widget in flutter listview? 如何在 Flutter 中围绕图像小部件浮动文本小部件 - How can I float Text Widget around an Image Widget in Flutter Flutter 何时使用 SF Pro Display 或 SF Pro Text 以及如何将它们分配给 Text 小部件? - Flutter when is SF Pro Display or SF Pro Text used and how to assign them to a Text widget? 使用 Flutter GetX 和 API,如何将 API 数据显示到 Text 小部件中? - Using Flutter GetX and an API, how do I display the API data into a Text widget? 如何从 function 获取价值并在文本小部件 flutter 中显示 - how to get value from function and display in text widget flutter 将列表中的文本设置为文本小部件 flutter - Set text from list to Text Widget flutter 我如何从 api 的 get 方法中获取一个数字,并将其显示在 flutter 的文本小部件中(我的 api 仅返回一个整数)不是 Z4666DEEC76ZDF2DFCA46438 - how can i get a number from a get method from an api and display it in a text widget in flutter (my api return just an integer) not in json format 在 Flutter 中,当子部件的构建方法中没有回调时,如何从子部件读取数据? - In Flutter, how can I read data from a child widget when callbacks are not available within the build method of the child? 如何使用提供者/状态管理(在颤动中)根据值的变化显示或隐藏小部件? - How can I display or hide widget according to change in value using provider / State management( In flutter)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM