简体   繁体   中英

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 .

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.

questionnaires.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.

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

"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 . This is good for small and sample projects while you're testing out 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.

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. served via REST APIs, then retrieve it using the http plugin for Flutter.

More on:

Output:

图像 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM