0

я совсем новичок во Flutter, и поэтому совсем не могу понять, как к виджету текста и кнопка привязать функции.

Что у меня есть: рыба - текст, кривое поле ввода и иконки.

Что нужно: чтобы текст увеличивался при нажатии на иконки, и от цифры, введенной в поле ввода.

Вот мой код:


void main() {
  runApp(MaterialApp(
      title: 'First App',
      home: Scaffold(
          appBar: AppBar(title: Text("Основы компоновки"), centerTitle: true),
          body: Stack(
              children: [
              Container(
              width: 150,
              height: 50,
              child: TextField(
                  decoration:InputDecoration(
                    enabledBorder: const OutlineInputBorder(
                      borderSide: const BorderSide(color: Colors.yellow, width: 1.5),
                    ),
                labelText: 'Enter font size',
                  )
              )
                ),
                Align(
                    alignment: Alignment.topLeft,
                    child: const Icon(Icons.add_circle,
                    )
                ),
                Align(
                    alignment: Alignment.topRight,
                    child: const Icon(Icons.remove_circle,
                    )
                ),
                Align(
                    alignment: Alignment(3,-0.3),
                    child: Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
                    )
                )
      ]
          )
      )
  )
  );
}

введите сюда описание изображения

Пожалуйста, объясните хотя бы немного, куда двигаться

Я предполагаю, что увеличение/уменьшение будет связано с инкриментом, но не представляю, как привязать его к тесту и как вообще это скомпоновать

1
  • Выложите пример на DartPad.
    – nazarpunk
    17 окт 2021 в 9:20

1 ответ 1

0

Чтобы понять что тут происходит вам необходимо ознакомиться с StatefulWidget

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      title: 'First App',
      home: Scaffold(
        appBar: AppBar(title: Text("Основы компоновки"), centerTitle: true),
        body: MyWidget(),
      ),
    ),
  );
}

class MyWidget extends StatefulWidget {
  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  TextEditingController controller;
  double fontSize = 14;

  @override
  void initState() {
    controller = TextEditingController();
    controller.addListener(listener);

    super.initState();
  }

  @override
  void dispose() {
    controller.removeListener(listener);
    controller.dispose();
  }

  void listener() {
    double size = double.tryParse(controller.text);
    if (size != null) {
      setState(() {
        fontSize = size;
      });
    }
  }

  void increment() {
    setState(() {
      fontSize++;
    });
  }

  void decrement() {
    setState(() {
      fontSize--;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          width: 150,
          height: 50,
          child: TextField(
            controller: controller,
            decoration: InputDecoration(
              enabledBorder: const OutlineInputBorder(
                borderSide: const BorderSide(color: Colors.yellow, width: 1.5),
              ),
              labelText: 'Enter font size',
            ),
          ),
        ),
        Align(
          alignment: Alignment.topLeft,
          child: IconButton(
            icon: const Icon(
              Icons.add_circle,
            ),
            onPressed: () {
              increment();
            },
          ),
        ),
        Align(
          alignment: Alignment.topRight,
          child: IconButton(
            icon: const Icon(
              Icons.remove_circle,
            ),
            onPressed: () {
              decrement();
            },
          ),
        ),
        Align(
          alignment: Alignment(3, -0.3),
          child: Text(
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
            style: TextStyle(fontSize: fontSize),
          ),
        ),
      ],
    );
  }
}
2
  • Cпасибо! Очень помогло!
    – Mirra Navy
    2 ноя 2021 в 8:53
  • Если ответ подходит, его можно отметить галкой (слева, под стрелками), как правильный вариант.
    – MiT
    2 ноя 2021 в 9:36

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.