Во флаттере, как мне сохранить ввод TextBox из сгенерированных текстовых полей? - PullRequest
0 голосов
/ 15 апреля 2020

Ниже приведен мой полный код, единственное, что вам нужно сделать, чтобы запустить его, это добавить «http: any» к зависимостям в pubspe c .yaml.

Код выполняет захват JSON ввод из источника, и для каждой записи в ленте json создайте карточку. Теперь для каждого вопроса я хочу, чтобы пользователь предоставил ответ, поэтому, когда я добавляю кнопку внизу, появляется всплывающее окно с ответами (которое я позже опубликую на своем сервере). Это выглядело бы примерно так:

Q1: «три»

Q2: «тридцать»

Q3: «Какой-то мов ie символ»

Q4: «Уолтер Уайт»

(я проверю свои ответы позже)

Мой json размещен под кодом.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;


Future<List<Question>> fetchQuestions(http.Client client) async {
  final response =
      await client.get('https://jsonblob.com/api/jsonBlob/a5885973-7f02-11ea-b97d-097037d3b153');

  // Use the compute function to run parsePhotos in a separate isolate
  return compute(parseQuestion, response.body);
}

// A function that will convert a response body into a List<Photo>
List<Question> parseQuestion(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Question>((json) => Question.fromJson(json)).toList();
}

class Question {
  final int id;
  final String question;
  final String answer;

  Question({this.id, this.question, this.answer});

  factory Question.fromJson(Map<String, dynamic> json) {
    return Question(
      id: json['id'] as int,
      question: json['question'] as String,
      answer: json['answer'] as String
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Isolate Demo';

    return MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

 class MyHomePage extends StatelessWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Padding(
        child: FutureBuilder<List<Question>>(
          future: fetchQuestions(http.Client()),
          builder: (context, snapshot) {
            if (snapshot.hasError) print(snapshot.error);

            return snapshot.hasData
                ? QuestionList(questions: snapshot.data)
                : Center(child: CircularProgressIndicator());
          },
        ),
        padding: EdgeInsets.fromLTRB(1.0, 10.0, 1.0, 10.0),
      ),
    );
  }
}

class QuestionList extends StatelessWidget {
  final List<Question> questions;

  QuestionList({Key key, this.questions}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: questions.length,
      itemBuilder: (context, index) {
        return Column(
          children: <Widget>[
            Container(
                constraints: BoxConstraints.expand(
                  height: Theme.of(context).textTheme.display1.fontSize * 1.1 +
                      200.0,
                ),
                color: Colors.blueGrey,
                alignment: Alignment.center,
                child: Card(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      ListTile(

                        title: Text(questions[index].id.toString()),
                        subtitle: Text(questions[index].question),
                      ),
                      new TextFormField(
                      decoration: new InputDecoration(
                        labelText: "Answer Question",
                        fillColor: Colors.white,
                        border: new OutlineInputBorder(
                          borderRadius: new BorderRadius.circular(25.0),
                          borderSide: new BorderSide(
                          ),
                        ),
                      ),
                      validator: (val) {
                        if(val.length==0) {
                          return "Type your answer here";
                        }else{
                          return null;
                        }
                      },
                      keyboardType: TextInputType.text,
                      style: new TextStyle(
                        fontFamily: "Poppins",
                      ),
                    ),

                        /*
                        // make buttons use the appropriate styles for cards
                        ButtonBar(
                          children: <Widget>[                         
                            RaisedButton(
                              color: Colors.lightBlue,
                              hoverColor: Colors.blue,
                              child: const Text('Open'),
                              onPressed: () {/* ... */},
                            ),
                          ],
                        ),
                     */
                    ],
                  ),
                )),
          ],
        );
      },
    );
  }
}



[
    {
        "id" : 1,
        "question" : "what is one plus two",
        "answer": "three"
    },
    {
        "id" : 2,
        "question" :  "what is five times 6",
        "answer": "thirty"
    },
    {
        "id" : 3,
        "question" : "Who said show me the money",
        "answer": "Cuba Gooding Jnr"
    },
    {
        "id" : 4,
        "question" : "who said I am the danger",
        "answer": "Walter White"
    }
]

1 Ответ

0 голосов
/ 15 апреля 2020

Рассмотрите возможность подключения TextEditingController к TextFormField через свойство controller. Вы можете получить доступ к тексту, находящемуся в данный момент в TextField, используя поле контроллера text.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...