一些会导致布局错误的情况
FlutterAndroid
阅读时间: 2 min
在 Flutter 里,Slider 组件的尺寸默认会依据父组件的约束自动调整,这时候放置到Column中,会显示失败,解决办法是包裹在SizedBox中,限制其尺寸。
以及如何获取屏幕宽度。
核心代码
1import 'dart:convert';2import 'dart:ffi';3import 'package:http/http.dart' as http;4
5import 'package:flutter/material.dart';6import 'package:logging/logging.dart';7import 'package:path/path.dart';8
9//10class TestPage extends StatefulWidget {11 const TestPage({super.key});12
13 @override14 State<TestPage> createState() => _TestPageState();15}50 collapsed lines
16
17class _TestPageState extends State<TestPage> {18 // 创建日志记录实例,命名为 'SendPage'19 final Logger logger = Logger('SendPage');20 double rating = 0.0;21
22 @override23 Widget build(BuildContext context) {24 double screenWidth = MediaQuery.of(context).size.width;25
26 return Scaffold(27 appBar: AppBar(28 backgroundColor: Theme.of(context).colorScheme.inversePrimary,29 title: const Text("记录书摘"),30 ),31 body: Padding(32 padding: const EdgeInsets.all(16.0),33 child: Center(34 child: // 书籍评分滑动条35 Column(36 mainAxisAlignment: MainAxisAlignment.center,37 mainAxisSize: MainAxisSize.min,38 children: [39 ListTile(40 // 设置最小垂直内边距41 minVerticalPadding: 16,42 title: const Text('书籍评分'),43 subtitle: Text('$rating'),44 trailing: SizedBox(45 width: screenWidth * 0.55,46 child: Slider(47 value: rating,48 min: 0.0,49 max: 5.0,50 divisions: 10,51 onChanged: (value) {52 setState(() {53 rating = value;54 });55 },56 ),57 ),58 ),59 ],60 ),61 ),62 ), // This trailing comma makes auto-formatting nicer for build methods.63 );64 }65}