Флаттер AlertDialog с ListView и нижней TextField - PullRequest
1 голос
/ 07 апреля 2020

Я работаю над проектом Flutter, и я пытался создать AlertDialog, похожий на диалог опции , указанный в Руководстве по MaterialDesign , но с TextInput внизу.

I мне удалось получить что-то похожее на то, что я хочу, но есть проблема, которую я не могу решить: когда пользователь нажимает на TextInput и появляется клавиатура, я бы хотел, чтобы TextInput находился поверх клавиатуры, а представление списка становилось меньше на оси Y (вот почему я просто устанавливаю maxHeight на ConstrainedBox), чтобы пользователь мог видеть, что он пишет, но я получаю прямо противоположное, просмотр списка сохраняет тот же размер, а InputText не виден.

Я попытался изменить представление списка с помощью столбца, вложенного в SingleChildScrollView, или обернуть весь исходный столбец в SingleChildScrollView, но, похоже, ни один из них не работает. Это мой текущий код:

@override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.title),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(20))
      ),
      actions: <Widget>[
        FlatButton(
          child: const Text('CANCEL'),
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          textColor: Theme.of(context).accentColor,
          onPressed: () {
            widget.onCancel();
          },
        ),
        FlatButton(
          child: const Text('OK'),
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          textColor: Theme.of(context).accentColor,
          onPressed: () {
            widget.onOk();
          },
        ),
      ],
      content: Container(
        width: double.maxFinite,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Divider(),
            ConstrainedBox(
              constraints: BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height*0.4,
              ),
              child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: widget.exercises.length,
                  itemBuilder: (BuildContext context, int index){
                    return RadioListTile(
                        title: Text(widget.exercises[index].name),
                        value: index,
                        groupValue: _selected,
                        onChanged: (value){
                          setState(() {
                            _selected = index;
                          });
                        }
                    );
                  }
              ),
            ),
            Divider(),
            TextField(
              autofocus: false,
              maxLines: 1,
              style: TextStyle(fontSize: 18),
              decoration: new InputDecoration(
                border: InputBorder.none,
                hintText: widget.hintText,
              ),
            ),
          ],
        ),
      ),
    );
  }

Может ли кто-нибудь помочь мне?

Большое спасибо !!

1 Ответ

1 голос
/ 08 апреля 2020

Вы можете скопировать и запустить полный код ниже
Вы можете в content использовать SingleChildScrollView
фрагмент кода

 content: SingleChildScrollView(
        child: Container(
          width: double.maxFinite,

рабочая демонстрация

enter image description here

полный код

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class Exercise {
  String name;
  Exercise({this.name});
}

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

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

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<Exercise> exercises = [
    Exercise(name: 'A'),
    Exercise(name: 'B'),
    Exercise(name: 'C'),
    Exercise(name: 'D'),
    Exercise(name: 'E'),
    Exercise(name: 'F'),
    Exercise(name: 'G')
  ];
  int _selected;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.title),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(20))),
      actions: <Widget>[
        FlatButton(
          child: const Text('CANCEL'),
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          textColor: Theme.of(context).accentColor,
          onPressed: () {
            //widget.onCancel();
          },
        ),
        FlatButton(
          child: const Text('OK'),
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          textColor: Theme.of(context).accentColor,
          onPressed: () {
            //widget.onOk();
          },
        ),
      ],
      content: SingleChildScrollView(
        child: Container(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Divider(),
              ConstrainedBox(
                constraints: BoxConstraints(
                  maxHeight: MediaQuery.of(context).size.height * 0.4,
                ),
                child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: exercises.length,
                    itemBuilder: (BuildContext context, int index) {
                      return RadioListTile(
                          title: Text(exercises[index].name),
                          value: index,
                          groupValue: _selected,
                          onChanged: (value) {
                            setState(() {
                              _selected = index;
                            });
                          });
                    }),
              ),
              Divider(),
              TextField(
                autofocus: false,
                maxLines: 1,
                style: TextStyle(fontSize: 18),
                decoration: new InputDecoration(
                  border: InputBorder.none,
                  hintText: "hint",
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
...