FloatingActionButton 在 Flutter 应用程序中不起作用

问题描述 投票:0回答:1

嗨,我正在尝试使用 flutter 为我的应用程序创建按钮,但我使用的不起作用

floatingActionButton: FloatingActionButton(
Child:Text('click'),
)

'这是我使用过的代码,但仍然无法工作

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('Waybill App'),
        centerTitle: true,
      ),
      body: Center(
        child: Text('Welcome to Waybill Me'),
      ),
    floatingActionButton: FloatingActionButton(
      child: Text('click'),
    ),
     ),
      ),
    ),
  ));
}
flutter floating-action-button
1个回答
0
投票

您没有将

onPressed
参数添加到您的
FloatingActionButton()
小部件中,这是必需的!试试这个:

创建一个像这样的自定义视图小部件:

import 'package:flutter/material.dart';

class CustomView extends StatelessWidget {
  const CustomView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Waybill App'),
        centerTitle: true,
      ),
      body: const Center(
        child: Text('Welcome to Waybill Me'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          /*implement your own logic here,
             what do you want to happen when the user taps on this button
            you can do navigating / 
                       showing Dialogs /
                       sending and fetching data /
                       changing the state of the widget ... */
        },
        child: const Text('Tap'),
      ),
    );
  }
}

现在您可以轻松地将

CustomView
小部件传递到您想要使用它的任何地方;例如,让我们将您的代码更改为:

import 'package:flutter/material.dart';
import 'package:stack_overflow_questions/new.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter ShowCase',
      theme: ThemeData(
        primaryColor: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      //pass to the CustomView to the "home:" in here 
      home: const CustomView(),
    );
  }
} 
© www.soinside.com 2019 - 2024. All rights reserved.