Home > Mobile >  How do I add a containerwidget? That I can click and have an answer
How do I add a containerwidget? That I can click and have an answer

Time:11-12

I want to leave this container as a button, which I can click.

Container(

        margin: const EdgeInsets.all(15.0),
        padding: const EdgeInsets.all(3.0),
        decoration: BoxDecoration(
        border: Border.all(color: Colors.blueAccent)
        ),
        child: Text("AAAAAA"),
      )

CodePudding user response:

Wrap it with inkwell,

InkWell(
   onTap:(){},//call your function here 
   child: Container(
        margin: const EdgeInsets.all(15.0),
        padding: const EdgeInsets.all(3.0),
        decoration: BoxDecoration(
        border: Border.all(color: Colors.blueAccent)
        ),
        child: Text("AAAAAA"),
      ),
),

CodePudding user response:

You can either using InkWell or GestureDetector something like this:

class MyButton extends StatefulWidget {
  final VoidCallback onTap;
  const MyButton(this.onTap, {Key? key}) : super(key: key);

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

class _MyButtonState extends State<MyButton> {
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: widget.onTap,
      child: Container(
        margin: const EdgeInsets.all(15.0),
        padding: const EdgeInsets.all(3.0),
        decoration: BoxDecoration(border: Border.all(color: Colors.blueAccent)),
        child: Text("AAAAAA"),
      ),
    );
  }
}

then you can use it like this:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "SAMPLE",
      home: SafeArea(
        child: Scaffold(
            appBar: AppBar(
              title: Text("Demo Home Page"),
            ),
            body: MyButton(() {
              print("Hello");
            })),
      ),
    );
  }
}

Result:

enter image description here

  • Related