无法在与 Firebase 相连的 Container 上使用 InkWell 创建按钮

huangapple go评论62阅读模式
英文:

Can't create a button using InkWell on a Container which is also connected with Firebase

问题

错误出现在第51行,因为在 buildDoctors 函数中,context 变量未定义。要解决这个问题,您可以将 context 作为参数传递给 buildDoctors 函数。此外,您可以使用 Navigator 来导航到新页面,并将所需的信息传递给新页面。以下是修复您的代码并实现每个列表项都是按钮的示例:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

import 'AddDoctor.dart';

class HospitalDoctorList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFD9E4EE),
      appBar: AppBar(
        title: const Text('Doctor List'),
      ),
      body: StreamBuilder<List<Doctors>>(
        stream: readUsers(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Text('Something went wrong! ${snapshot.error}');
          } else if (snapshot.hasData) {
            final doctors = snapshot.data!;
            return ListView(
              children: doctors.map((doctor) => buildDoctors(context, doctor)).toList(),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        }),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.blue,
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => AddDoctor(),
            ),
          );
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget buildDoctors(BuildContext context, Doctors doctors) {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => DoctorDetailsPage(doctor: doctors),
              ),
            );
          },
          child: Container(
            // Your existing code for displaying doctor details
          ),
        ),
      ),
    );
  }

  Stream<List<Doctors>> readUsers() => FirebaseFirestore.instance
      .collection('DoctorList')
      .snapshots()
      .map((snapshot) =>
          snapshot.docs.map((doc) => Doctors.fromJson(doc.data())).toList());
}

class Doctors {
  // Your existing Doctors class definition
}

class DoctorDetailsPage extends StatelessWidget {
  final Doctors doctor;

  DoctorDetailsPage({required this.doctor});

  @override
  Widget build(BuildContext context) {
    // Create a new page to display doctor details based on the selected doctor.
    // You can use the 'doctor' property to access the selected doctor's information.
    return Scaffold(
      appBar: AppBar(
        title: Text(doctor.name),
      ),
      body: Center(
        child: Column(
          // Display doctor details here
        ),
      ),
    );
  }
}

上述代码中,我们将 context 作为参数传递给 buildDoctors 函数,并创建了一个新的 DoctorDetailsPage 页面来显示所选医生的详细信息。在 buildDoctors 函数中,当用户点击医生的列表项时,会导航到这个新页面,并将所选医生的信息传递给新页面。

英文:

I am trying to create a list which is fetched from Firebase. Now I want to make each list a button which will take me to a new page (also each page will also give different info based on the list a selected). But I can't wrap the container on inkwell.

Here is my code:

import &#39;package:cloud_firestore/cloud_firestore.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;AddDoctor.dart&#39;;
class HospitalDoctorList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFD9E4EE),
appBar: AppBar(
title: const Text(&#39;Doctor List&#39;),
),
body: StreamBuilder&lt;List&lt;Doctors&gt;&gt;(
stream: readUsers(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(&#39;Something went wrong! ${snapshot.error}&#39;);
} else if (snapshot.hasData) {
final doctors = snapshot.data!;
return ListView(
children: doctors.map(buildDoctors).toList(),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
}),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.blue,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =&gt; AddDoctor(),
),
);
},
child: const Icon(Icons.add),
),
);
}
Widget buildDoctors(Doctors doctors) =&gt; SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(10),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =&gt; AddDoctor(),
),
);
},
child: Container(
height: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.white60,
),
child: Row(
//mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: &lt;Widget&gt;[
Image.asset(
&#39;assets/PKC-Pics_0.jpg&#39;,
height: double.infinity,
),
const SizedBox(width: 10),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: &lt;Widget&gt;[
Text(
(doctors.name),
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
),
),
Text(
doctors.specialist,
style: const TextStyle(
fontSize: 20,
//fontWeight: FontWeight.bold,
),
),
Text(
doctors.hospital,
style: const TextStyle(
fontSize: 20,
//fontWeight: FontWeight.bold,
),
),
Text(
&#39;${doctors.age}&#39;,
style: const TextStyle(
fontSize: 20,
//fontWeight: FontWeight.bold,
),
),
],
),
],
),
),
),
),
);
Stream&lt;List&lt;Doctors&gt;&gt; readUsers() =&gt; FirebaseFirestore.instance
.collection(&#39;DoctorList&#39;)
.snapshots()
.map((snapshot) =&gt;
snapshot.docs.map((doc) =&gt; Doctors.fromJson(doc.data())).toList());
}
class Doctors {
String id;
final String name;
final int age;
final String hospital;
final String specialist;
Doctors({
this.id = &#39;&#39;,
required this.name,
required this.age,
required this.hospital,
required this.specialist,
});
static Doctors fromJson(Map&lt;String, dynamic&gt; json) =&gt; Doctors(
id: json[&#39;id&#39;],
name: json[&#39;name&#39;],
age: json[&#39;age&#39;],
hospital: json[&#39;hospital&#39;],
specialist: json[&#39;specialist&#39;],
);
}

The error is on Line 51:

Undefined name 'context'.
Try correcting the name to one that is defined, or defining the name.

How can I fix it and how to make each list a button and go to a new page where that page will give me the information based on the list i pressed?

答案1

得分: 1

你正在尝试在构建方法之外访问 BuildContext。您可以将 BuildContext 传递给 "buildDoctors" 方法,如下所示:

Widget buildDectors(BuildContext context, Doctors doctors) => ...
英文:

You are trying to access the BuildContext outside the build method.
What you could do is pass the BuildContext to the "buildDoctors" method, like following:

Widget buildDectors(BuildContext context, Doctors doctors) =&gt; ...

huangapple
  • 本文由 发表于 2023年2月13日 23:08:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定