一些会导致布局错误的情况

youyu 发布于 19 天前 200 次阅读


在 Flutter 里,Slider 组件的尺寸默认会依据父组件的约束自动调整,这时候放置到Column中,会显示失败,解决办法是包裹在SizedBox中,限制其尺寸。

以及如何获取屏幕宽度。

核心代码

import 'dart:convert';
import 'dart:ffi';
import 'package:http/http.dart' as http;

import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart';

//
class TestPage extends StatefulWidget {
  const TestPage({super.key});

  @override
  State
<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State
<TestPage> {
  // 创建日志记录实例,命名为 'SendPage'
  final Logger logger = Logger('SendPage');
  double rating = 0.0;

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("记录书摘"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: // 书籍评分滑动条
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                // 设置最小垂直内边距
                minVerticalPadding: 16,
                title: const Text('书籍评分'),
                subtitle: Text('$rating'),
                trailing: SizedBox(
                  width: screenWidth * 0.55,
                  child: Slider(
                    value: rating,
                    min: 0.0,
                    max: 5.0,
                    divisions: 10,
                    onChanged: (value) {
                      setState(() {
                        rating = value;
                      });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}